package com.liu.qqRobot.myself.handler;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.BetweenFormatter;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.liu.common.content.RedisKeyInterface;
import com.liu.common.utils.HtmlToImageUtils;
import com.liu.common.utils.QQClientUtils;
import com.liu.mybatisPlus.q.service.QGroupUserOperationQuantityService;
import com.liu.qqRobot.event.entity.dto.EventReportingDTO;
import com.liu.qqRobot.q.enums.OperationTypeEnum;
import freemarker.template.TemplateException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class CircuitHandler {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private QGroupUserOperationQuantityService qGroupUserOperationQuantityService;

    private final static Map<String, List<String>> ordinaryCircuitMap = new HashMap<>();

    private final static Map<String, List<String>> hardCircuitMap = new HashMap<>();

    static {
        ordinaryCircuitMap.put("1", Arrays.asList("Excalibur", "Trinity", "Ember"));
        ordinaryCircuitMap.put("2", Arrays.asList("Loki", "Mag", "Rhino"));
        ordinaryCircuitMap.put("3", Arrays.asList("Ash", "Frost", "Nyx"));
        ordinaryCircuitMap.put("4", Arrays.asList("Saryn", "Vauban", "Nova"));
        ordinaryCircuitMap.put("5", Arrays.asList("Nekros", "Valkyr", "Oberon"));
        ordinaryCircuitMap.put("6", Arrays.asList("Hydroid", "Mirage", "Limbo"));
        ordinaryCircuitMap.put("7", Arrays.asList("Mesa", "Chroma", "Atlas"));
        ordinaryCircuitMap.put("8", Arrays.asList("Ivara", "Inaros", "Titania"));
        ordinaryCircuitMap.put("9", Arrays.asList("Nidus", "Octavia", "Harrow"));
        ordinaryCircuitMap.put("10", Arrays.asList("Gara", "Khora", "Revenant"));
        ordinaryCircuitMap.put("11", Arrays.asList("Garuda", "Baruuk", "Hilaryn"));
        hardCircuitMap.put("1", Arrays.asList("布莱顿", "拉托", "空刃", "帕里斯", "苦无"));
        hardCircuitMap.put("2", Arrays.asList("野猪", "咖玛腕甲枪", "安格斯壮", "蛇发女妖", "夺魄死神"));
        hardCircuitMap.put("3", Arrays.asList("玻之武杖", "拉特昂", "盗贼", "弗拉克斯", "斯特朗"));
        hardCircuitMap.put("4", Arrays.asList("雷克斯", "执法者", "螺钉步枪", "野马", "陶瓷匕首"));
        hardCircuitMap.put("5", Arrays.asList("托里德", "毒囊双枪", "恶脓双斧", "米特尔", "原子矿融炮"));
        hardCircuitMap.put("6", Arrays.asList("认知&amp;冲击", "月神", "瓦斯托", "海波单剑", "伯斯顿"));
        hardCircuitMap.put("7", Arrays.asList("席尔火枪", "西伯利亚冰锤", "恐惧", "绝望", "憎恨"));
        hardCircuitMap.put("8", Arrays.asList("德拉", "席芭莉丝", "锡斯特", "暗杀者", "翁"));
    }

    /**
     * 处理事件
     * @param data 信息内容
     * @param groupId 群号
     * @param userId 发送人QQ号
     */
    public void handler(EventReportingDTO.Message.Data data, Long groupId, Long userId, Boolean isGroup) {
        String hardCircuit = redisTemplate.opsForValue().get(RedisKeyInterface.HARD_CIRCUIT_POLLING_REDIS_KEY);
        String ordinaryCircuit = redisTemplate.opsForValue().get(RedisKeyInterface.ORDINARY_CIRCUIT_POLLING_REDIS_KEY);
        String circuitUpdateTime = this.getCircuitUpdateTime();
        int nextOrdinaryCircuit = 1;
        if (ordinaryCircuit != null) {
            int currentPolling = Integer.parseInt(ordinaryCircuit);
            nextOrdinaryCircuit = currentPolling + 1;
            if (nextOrdinaryCircuit > 11) {
                nextOrdinaryCircuit = 1;
            }
        }
        int nextHardCircuit = 1;
        if (hardCircuit != null) {
            int currentPolling = Integer.parseInt(hardCircuit);
            nextHardCircuit = currentPolling + 1;
            if (nextHardCircuit > 8) {
                nextHardCircuit = 1;
            }
        }
        Map<String, Object> templateParam = new HashMap<>();
        templateParam.put("ordinaryCircuit", ordinaryCircuitMap.get(ordinaryCircuit));
        templateParam.put("nextOrdinaryCircuit", ordinaryCircuitMap.get(String.valueOf(nextOrdinaryCircuit)));
        templateParam.put("hardCircuit", hardCircuitMap.get(hardCircuit));
        templateParam.put("nextHardCircuit", hardCircuitMap.get(String.valueOf(nextHardCircuit)));
        templateParam.put("circuitUpdateTime", circuitUpdateTime);
        try {
            HtmlToImageUtils.htmlToImage("circuitTemplate.html", templateParam,
                    "src/main/resources/picture/circuit.png", 2200);
            File file = new File("src/main/resources/picture/circuit.png");
            String encode = Base64.encode(file);
            String msg = "[CQ:at,qq=" + userId + "]\n[CQ:image,file=base64://" + encode+ ",type=show,subType=0]";
            QQClientUtils.sendMsg(msg, userId, groupId, isGroup);
            qGroupUserOperationQuantityService.statisticsOperationQuantityByType(groupId, userId, OperationTypeEnum.CIRCUIT);
        } catch (IOException | ParserConfigurationException | SAXException | TemplateException e) {
            log.error("获取订单展示模板失败:{}", e.getMessage(), e);
//            QQClientUtils.sendGroupMsg("[CQ:at,qq=" + userId + "]\n获取订单展示模板失败，请联系制作人", userId, groupId, isGroup);
        }
    }

    /**
     * 获取回廊剩余时间
     * @return String
     */
    private String getCircuitUpdateTime() {
        // 获取当前日期对应下周时间
        DateTime nextWeek = DateUtil.nextWeek();
        // 获取下周第一天开头时间
        DateTime nextWeekFirstTime = DateUtil.beginOfWeek(nextWeek);
        // 获取当前时间与下周第一天开头时间，时间差
        return DateUtil.formatBetween(DateUtil.date(), nextWeekFirstTime, BetweenFormatter.Level.SECOND);
    }
}
